import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import { EditIndexModal } from '@/pages/OrderModule/common/components/EditIndexModal';
import React, { useState } from 'react';
import { useFilterFieldsConfig } from '../../store';
import Typography from "@/pages/OrderModule/common/components/Typography";
import { Alert, Button, Spin, message } from "antd";
import { updateFieldConfig } from '../../../OrderList/services';

const descEl = (
  <Typography as="s1">
    选择哪个筛选字段类别，哪个就会显示在筛选里
    <Typography as="s1" color="#999">
      (上下可拖动字段排序)
    </Typography>
  </Typography>
);

function resolveCheckedColumns(checkedColumns, originMap = {}) {
  const data = new Map();
  checkedColumns === null || checkedColumns === void 0
    ? void 0
    : checkedColumns.forEach((v) => {
      data.set(v.key, Object.hasOwnProperty.call(originMap, v.key) ? originMap[v.key] : false);
    });
  return data;
}

function flattenColumnConfigs(columnConfigs) {
  const data = [];
  function dfs(columnConfigs) {
    columnConfigs.forEach((config) => {
      data.push(config);
      if (config.childrenNode) {
        dfs(config.childrenNode);
      }
    });
  }
  dfs(columnConfigs);
  return data;
}

function mapToObject(map) {
  return Object.fromEntries(map.entries());
}
/**
 * 可编辑指标的table
 */
export const ControlFieldModal = React.memo(function (props) {
  const { checkingMap, updateCheckingMap } = useFilterFieldsConfig();

  const { visible, defaultCheckedColumns, columnConfigs = [], columns = [], rowKey, modalTitle, onVisibleChange, onColumnsConfigChange } = props;
  const [checked, setChecked] = useState(resolveCheckedColumns(defaultCheckedColumns, checkingMap));
  const [columnConfigsData, setColumnConfigsData] = useState(columnConfigs);
  const [commit, setCommit] = useState({ checked, columnConfigsData });
	const [loading, setLoading] = useState(false);

  const onCancel = (e) => {
    setChecked(commit.checked);
    setColumnConfigsData(commit.columnConfigsData);
    onVisibleChange?.(false);
  }

  const onOk = async (e) => {
    const checkingMap =  mapToObject(checked)
    setLoading(true)
    try {
      await updateFieldConfig({
        code: "ColsSettingOrderFilter",
        param: JSON.stringify(checkingMap)
      });
      
      checked.delete('dataIndex');
      setCommit({ checked, columnConfigsData });
      updateCheckingMap({ checkingMap });
      onVisibleChange?.(false);
      onColumnsConfigChange?.(columnConfigsData);
    } catch (error) {
      console.error(error)
      message.error('保存失败')
    }
    setLoading(false)
  }

  function swap(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  }

  const onAscChange = (key, field) => {
    let newColumnConfigs = [...columnConfigsData]
    const elem = newColumnConfigs.find(item => item.name === key)
    const index = elem?.childrenNode?.findIndex(item => item.field === field)
    if (index > 0) {
      swap(elem.childrenNode, index - 1, index);
      setColumnConfigsData(newColumnConfigs)
    }
  }

  const onDescChange = (key, field) => {
    let newColumnConfigs = [...columnConfigsData]
    const elem = newColumnConfigs.find(item => item.name === key)
    const index = elem?.childrenNode?.findIndex(item => item.field === field)
    let len =  elem?.childrenNode.length
    if (index < len - 1) {
      swap(elem.childrenNode, index + 1, index);
      setColumnConfigsData(newColumnConfigs)
    }
  }

  return (
    <CommonModal
      width={528}
      title={{
        title: '筛选字段设置',
      }}
      footer={
        <>
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" onClick={onOk}>
            保存
          </Button>
        </>
      }
      open={visible}
      onCancel={onCancel}
      onOk={onOk}
      destroyOnClose
    >
      <Alert style={{ marginBottom: "16px" }} message={descEl} />
      <Spin spinning={loading}>
        <EditIndexModal
          value={columnConfigsData.filter((el) => !el.hide)}
          onValueChange={setColumnConfigsData}
          checkedColumns={checked}
          onCheckedColumnsChange={(...val) => {
            setChecked(...val);
          }}
          onAscChange={onAscChange}
          onDescChange={onDescChange}
        />
      </Spin>
    </CommonModal>
  );
});
export default ControlFieldModal;
